package ciicos.work.service.impl;

import ciicos.base.model.filter.RuleInfo;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.util.GenUtil;
import ciicos.util.DateUtil;
import ciicos.util.GeneraterSwapUtil;
import ciicos.util.JsonUtil;
import ciicos.util.ServletUtil;
import ciicos.util.StringUtil;
import ciicos.util.UserProvider;
import ciicos.work.entity.WorkInfoEntity;
import ciicos.work.mapper.WorkInfoMapper;
import ciicos.work.model.workinfo.WorkInfoForm;
import ciicos.work.model.workinfo.WorkInfoPagination;
import ciicos.work.service.WorkInfoService;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

/**
 * 工单信息
 * 版本： V3.2.0
 * 版权：
 * 作者： 产研项目租
 * 日期： 2023-08-02
 */
@Service
@Slf4j
public class WorkInfoServiceImpl extends ServiceImpl<WorkInfoMapper, WorkInfoEntity> implements WorkInfoService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;


    @Override
    public List<WorkInfoEntity> getListNoNet(WorkInfoPagination workInfoPagination) {
        return getTypeListNoNet(workInfoPagination, workInfoPagination.getDataType());
    }

    @Override
    public List<WorkInfoEntity> getTypeListNoNet(WorkInfoPagination workInfoPagination, String dataType) {
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;

        QueryWrapper<WorkInfoEntity> workInfoQueryWrapper = new QueryWrapper<>();
        //获取当日任务
        workInfoQueryWrapper.lambda().eq(workInfoPagination.getFlag() == 1, WorkInfoEntity::getHappenDate, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        // 获取未下载的数据
        workInfoQueryWrapper.lambda().eq(WorkInfoEntity::getIsdownload, 0);

        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            workInfoQueryWrapper.lambda().in(WorkInfoEntity::getId, intersection);
        }
        // 过滤条件
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<WorkInfoEntity> page = new Page<>(workInfoPagination.getCurrentPage(), workInfoPagination.getPageSize());
                IPage<WorkInfoEntity> userIPage = this.page(page, workInfoQueryWrapper);
                return workInfoPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<WorkInfoEntity> list = new ArrayList();
                return workInfoPagination.setData(list, list.size());
            }
        } else {
            return this.list(workInfoQueryWrapper);
        }
    }

    @Override
    public List<WorkInfoEntity> getList(WorkInfoPagination workInfoPagination) {
        return getTypeList(workInfoPagination, workInfoPagination.getDataType());
    }

    @Override
    public List<WorkInfoEntity> getTypeList(WorkInfoPagination workInfoPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int workInfoNum = 0;
        QueryWrapper<WorkInfoEntity> workInfoQueryWrapper = new QueryWrapper<>();
        //获取当日任务
        workInfoQueryWrapper.lambda().eq(workInfoPagination.getFlag() == 1, WorkInfoEntity::getHappenDate, new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        //获取30天内的数据
        if (workInfoPagination.getFlag() == 2) {
            //当日
            LocalDate currentDate = LocalDate.now();
            System.out.println("当日" + currentDate);
            //头30天
            LocalDate minusDays = currentDate.minusMonths(1);
            System.out.println("减去" + minusDays);
            workInfoQueryWrapper.lambda().between(WorkInfoEntity::getHappenDate, minusDays, currentDate);
            if (workInfoPagination.getHappenDate() != null) {
                workInfoQueryWrapper.lambda().eq(WorkInfoEntity::getHappenDate, new Date(workInfoPagination.getHappenDate()));
            }
        }

        boolean pcPermission = true;
        boolean appPermission = true;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");

        if (workInfoPagination.getSource() != null && workInfoPagination.getSource().size() != 0) {
                workInfoQueryWrapper.lambda().in(WorkInfoEntity::getSource, workInfoPagination.getSource());
        }
        if (ObjectUtil.isNotEmpty(workInfoPagination.getSelectteam())) {
            workInfoNum++;
            workInfoQueryWrapper.lambda().in(WorkInfoEntity::getSelectteam, workInfoPagination.getSelectteam());

        }

        if (ObjectUtil.isNotEmpty(workInfoPagination.getQuestion())) {
            workInfoNum++;

            workInfoQueryWrapper.lambda().like(WorkInfoEntity::getQuestion, workInfoPagination.getQuestion());

        }


        if (workInfoPagination.isDcl()) {
            workInfoNum++;
            workInfoQueryWrapper.lambda().eq(WorkInfoEntity::getEnabledmark, 1);
            workInfoQueryWrapper.lambda().isNull(WorkInfoEntity::getHandleuserid);
        }

        if (workInfoPagination.isDcl()) {
            workInfoNum++;
            workInfoQueryWrapper.lambda().eq(WorkInfoEntity::getEnabledmark, 1);
            workInfoQueryWrapper.lambda().isNotNull(WorkInfoEntity::getHandleuserid);
            workInfoQueryWrapper.lambda().isNull(WorkInfoEntity::getConfirmuserid);
        }
        if (workInfoPagination.getFinishStatus() != null && workInfoPagination.getFinishStatus().size() != 0) {
//            for (String finishStatus : workInfoPagination.getFinishStatus()) {
                workInfoQueryWrapper.lambda().in(WorkInfoEntity::getFinishStatus, workInfoPagination.getFinishStatus());
//            }
        }

//        } else {
//            // app端
//            // 增加根据责任队的筛选
//            workInfoQueryWrapper.lambda().eq(WorkInfoEntity::getSelectteam, userProvider.get().getOrganizeId());
//        }


        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            workInfoQueryWrapper.lambda().in(WorkInfoEntity::getId, intersection);
        }


        //排序
        if (StringUtil.isEmpty(workInfoPagination.getSidx())) {
            workInfoQueryWrapper.lambda().orderByDesc(WorkInfoEntity::getHappenDate);
        } else {
            try {
                String sidx = workInfoPagination.getSidx();
                WorkInfoEntity workInfoEntity = new WorkInfoEntity();
                Field declaredField = workInfoEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                workInfoQueryWrapper = "asc".equals(workInfoPagination.getSort().toLowerCase()) ? workInfoQueryWrapper.orderByAsc(value) : workInfoQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        // 过滤条件

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<WorkInfoEntity> page = new Page<>(workInfoPagination.getCurrentPage(), workInfoPagination.getPageSize());
                IPage<WorkInfoEntity> userIPage = this.page(page, workInfoQueryWrapper);
                return workInfoPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<WorkInfoEntity> list = new ArrayList();
                return workInfoPagination.setData(list, list.size());
            }
        } else {
            return this.list(workInfoQueryWrapper);
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String
            tableName) {
        try {
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos) {
                String field = info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_")) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if ("sub-jnpf".equals(type) && !field.contains("_jnpf_")) {
                    continue;
                }
                String fieldName = field;
                String table = "";
                if (field.contains("-")) {
                    fieldName = field.split("-")[1];
                }
                if (field.contains("_jnpf_")) {
                    fieldName = field.split("_jnpf_")[1];
                    table = field.split("_jnpf_")[0];
                    table = table.replace("jnpf_", "");
                }
                if ("sub-jnpf".equals(type) && !tableName.equals(table)) {
                    continue;
                }
                Field declaredField = aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb = declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil = JsonUtil.getJsonToBean(info, GenUtil.class);
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        } catch (Exception e) {
            return wrapper;
        }
    }

    @Override
    public WorkInfoEntity getInfo(String id) {
        QueryWrapper<WorkInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WorkInfoEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(WorkInfoEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, WorkInfoEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(WorkInfoEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法


    //验证表单唯一字段
    @Override
    public String checkForm(WorkInfoForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }

        return countRecover;
    }


    @Override
    public List<WorkInfoEntity> getWorkInfo(String orgcode, Date start, Date end) {
        // 根据组织编码获取对应的资产类型

        LambdaQueryWrapper<WorkInfoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(WorkInfoEntity::getCreatortime, start, end);
        wrapper.orderByAsc(WorkInfoEntity::getCreatortime);
        wrapper.eq(WorkInfoEntity::getEnabledmark, 1);
        List<WorkInfoEntity> list = this.list(wrapper);
        // 筛选出该队下的工单
        ArrayList<WorkInfoEntity> res = new ArrayList<>();

        return res;
    }


    @Override
    public List<WorkInfoEntity> getAllWorkWithNoOrgCode(Date dayBegin, Date dayEnd) {
        return this.list(
                new LambdaQueryWrapper<WorkInfoEntity>()
                        .eq(WorkInfoEntity::getEnabledmark, 1)
                        .between(WorkInfoEntity::getCreatortime, dayBegin, dayEnd)
        );
    }

    @Override
    public List<WorkInfoEntity> getAllWorkWithStatus(Date dayBegin, Date dayEnd) {

        return this.list(
                new LambdaQueryWrapper<WorkInfoEntity>()
                        .between(WorkInfoEntity::getCreatortime, dayBegin, dayEnd)
                        .eq(WorkInfoEntity::getEnabledmark, 1)
                        .in(WorkInfoEntity::getStatus, 1, 2)

        );
    }


    @Autowired
    private WorkInfoService workInfoService;


    @Override
    public Integer getCountWithDateAndType(Date begin, Date end, String balconyCode) {
        return baseMapper.getCountWithDateAndType(begin, end, balconyCode);
    }

    @Override
    public Double getHoursBetweenDate(String id, Date begin, Date end) {
        List<WorkInfoEntity> workList = workInfoService.getWorkInfo(id, begin, end);
        Double workHoursSum = 0d;
        for (WorkInfoEntity item : workList) {
            if (item.getStarttime() == null && item.getEndtime() == null) {
                continue;
            }
            Double hours = DateUtil.computeTwoDateDifference(item.getStarttime(), item.getEndtime());
            workHoursSum += hours;
        }
        return workHoursSum;
    }


}
